package com.nothing5lose.iwillbeback;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.nothing5lose.iwillbeback.utils.GMapV2Direction;
import org.w3c.dom.Document;

import java.util.ArrayList;

class GetNavigationTask extends AsyncTask<Pair<LatLng,LatLng>,Void,Document> {
    private GMapV2Direction mNavigator;
    private Context mContext;
    private GoogleMap mMap;

    public GetNavigationTask(Context parent,GoogleMap map){
        super();
        this.mContext = parent;
        this.mMap = map;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mNavigator = new GMapV2Direction();
    }

    @Override
    protected Document doInBackground(Pair<LatLng,LatLng>... params) {
        return  mNavigator.getDocument(params[0].first, params[0].second, GMapV2Direction.MODE_DRIVING);
    }

    @Override
    protected void onPostExecute(Document document) {
        super.onPostExecute(document);
        //Add Desination Maker
        if(null == mMap){
            return;
        }

        if (null != document){
            //Dump values
            dump(document);

            //Add polyline to the map
            ArrayList<LatLng> directionPoint = mNavigator.getDirection(document);
            final PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

            for(int i = 0 ; i < directionPoint.size() ; i++) {
                rectLine.add(directionPoint.get(i));
            }
            mMap.addPolyline(rectLine);
        }else{
            Toast.makeText(mContext, "Get Navigation fail!", Toast.LENGTH_SHORT).show();
        }

    }

    private void dump(Document document) {
        Log.e("LTT", "duration_value = " + mNavigator.getDurationValue(document));
        Log.e("LTT", "duration_text = " + mNavigator.getDurationText(document));

        Log.e("LTT","start_address = "+mNavigator.getStartAddress(document));
        Log.e("LTT","end_address = "+mNavigator.getEndAddress(document));

        Log.e("LTT","distance_value = "+mNavigator.getDistanceValue(document));
        Log.e("LTT","distance_text = "+mNavigator.getDistanceText(document));

        Log.e("LTT","copy_right = "+mNavigator.getCopyRights(document));
    }
}
